import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { AlipaySdk } from 'alipay-sdk';

export interface AlipayCreatePaymentParams {
  outTradeNo: string;
  totalAmount: number;
  subject: string;
  body?: string;
  returnUrl?: string;
}

@Injectable()
export class AlipayService {
  private sdk: AlipaySdk;
  private alipayConfig: any;

  constructor(private readonly configService: ConfigService) {
    try {
      // 从配置中读取支付宝配置
      this.alipayConfig = this.configService.get('payment.alipay');

      // 检查配置是否存在
      if (!this.alipayConfig) {
        console.warn('⚠️ 支付宝配置未设置，跳过初始化');
        return;
      }

      console.log('🔍 支付宝配置:', {
        hasAppId: !!this.alipayConfig.appId,
        hasPrivateKey: !!this.alipayConfig.privateKey,
        hasAlipayPublicKey: !!this.alipayConfig.alipayPublicKey,
        gateway: this.alipayConfig.gateway,
      });

      // ✅ 使用正确的配置参数
      const params: any = {
        appId: this.alipayConfig.appId,
        privateKey: this.alipayConfig.privateKey,
        alipayPublicKey: this.alipayConfig.alipayPublicKey,
        gateway: this.alipayConfig.gateway,
        keyType: 'PKCS1',
        signType: 'RSA2',
      };

      this.sdk = new AlipaySdk(params);
      console.log('✅ 支付宝SDK初始化成功');
    } catch (error) {
      console.error('❌ 支付宝SDK初始化失败:', error);
      console.error('错误详情:', error?.message || error);
      // 不抛出错误，允许服务启动（支付功能将不可用）
      console.warn('⚠️ 支付宝支付功能将不可用');
    }
  }

  /**
   * 创建PC网站支付
   */
  async createPagePay(params: AlipayCreatePaymentParams): Promise<string> {
    try {
      const bizContent = {
        subject: params.subject,
        out_trade_no: params.outTradeNo,
        total_amount: params.totalAmount.toFixed(2),
        body: params.body,
        product_code: 'FAST_INSTANT_TRADE_PAY',
      };

      const result = this.sdk.pageExecute('alipay.trade.page.pay', 'GET', {
        bizContent,
        returnUrl: params.returnUrl || this.alipayConfig.returnUrl,
      });

      console.log('支付宝PC支付创建成功:', params.outTradeNo);
      return result;
    } catch (error) {
      console.error('支付宝PC支付创建失败:', error);
      throw new Error('支付宝PC支付创建失败');
    }
  }

  /**
   * 创建手机网站支付
   */
  async createWapPay(params: AlipayCreatePaymentParams): Promise<string> {
    try {
      const bizContent = {
        subject: params.subject,
        out_trade_no: params.outTradeNo,
        total_amount: params.totalAmount.toFixed(2),
        body: params.body,
        product_code: 'QUICK_WAP_WAY',
        quit_url: params.returnUrl || this.alipayConfig.returnUrl,
      };

      const result = this.sdk.pageExecute('alipay.trade.wap.pay', 'GET', {
        bizContent,
        returnUrl: params.returnUrl || this.alipayConfig.returnUrl,
      });

      console.log('支付宝手机支付创建成功:', params.outTradeNo);
      return result;
    } catch (error) {
      console.error('支付宝手机支付创建失败:', error);
      throw new Error('支付宝手机支付创建失败');
    }
  }

  /**
   * 查询订单状态
   */
  async queryOrder(outTradeNo: string): Promise<any> {
    try {
      const bizContent = {
        out_trade_no: outTradeNo,
      };

      const result = await this.sdk.exec('alipay.trade.query', {
        bizContent,
      });

      return result;
    } catch (error) {
      console.error('支付宝订单查询失败:', error);
      throw new Error('支付宝订单查询失败');
    }
  }

  /**
   * 关闭订单
   */
  async closeOrder(outTradeNo: string): Promise<any> {
    try {
      const bizContent = {
        out_trade_no: outTradeNo,
      };

      const result = await this.sdk.exec('alipay.trade.close', {
        bizContent,
      });

      return result;
    } catch (error) {
      console.error('支付宝订单关闭失败:', error);
      throw new Error('支付宝订单关闭失败');
    }
  }

  /**
   * 申请退款
   */
  async refund(params: {
    outTradeNo: string;
    refundAmount: number;
    refundReason?: string;
    outRequestNo?: string;
  }): Promise<any> {
    try {
      const bizContent = {
        out_trade_no: params.outTradeNo,
        refund_amount: params.refundAmount.toFixed(2),
        refund_reason: params.refundReason || '用户申请退款',
        out_request_no:
          params.outRequestNo || `${params.outTradeNo}_refund_${Date.now()}`,
      };

      const result = await this.sdk.exec('alipay.trade.refund', {
        bizContent,
      });

      return result;
    } catch (error) {
      console.error('支付宝退款失败:', error);
      throw new Error('支付宝退款失败');
    }
  }

  /**
   * 验证支付宝回调签名
   */
  verifyNotify(params: any): boolean {
    try {
      return this.sdk.checkNotifySign(params);
    } catch (error) {
      console.error('支付宝回调验证失败:', error);
      return false;
    }
  }

  /**
   * 处理支付宝回调
   */
  handleNotify(params: any): {
    isValid: boolean;
    outTradeNo?: string;
    tradeNo?: string;
    tradeStatus?: string;
    totalAmount?: number;
  } {
    try {
      // 验证签名
      const isValid = this.verifyNotify(params);

      if (!isValid) {
        console.error('支付宝回调签名验证失败');
        return { isValid: false };
      }

      // 提取关键信息
      const {
        out_trade_no: outTradeNo,
        trade_no: tradeNo,
        trade_status: tradeStatus,
        total_amount: totalAmount,
      } = params;

      console.log('支付宝回调处理成功:', {
        outTradeNo,
        tradeNo,
        tradeStatus,
        totalAmount,
      });

      return {
        isValid: true,
        outTradeNo,
        tradeNo,
        tradeStatus,
        totalAmount: parseFloat(totalAmount),
      };
    } catch (error) {
      console.error('支付宝回调处理失败:', error);
      return { isValid: false };
    }
  }

  /**
   * 获取支付配置信息（用于前端）
   */
  getPaymentConfig() {
    return {
      appId: this.alipayConfig.appId,
      gateway: this.alipayConfig.gateway,
      // 不返回敏感信息
    };
  }
}




